package com.redisson.controller;

import com.redisson.annotate.RateLimiter;
import com.redisson.annotate.RateLimiters;
import com.redisson.dto.ApiResponseDto;
import com.redisson.dto.UserDto;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RateType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {

    private static Map<String, UserDto> map = new HashMap<String, UserDto>() {{
        put("BAT001", new UserDto("BAT001", "梁南生", 27, "研发部", 18000.0, LocalDateTime.of(2020, 5, 20, 9, 0, 0)));
        put("BAT002", new UserDto("BAT002", "包雅馨", 25, "财务部", 8800.0, LocalDateTime.of(2016, 11, 10, 8, 30, 0)));
        put("BAT003", new UserDto("BAT003", "罗考聪", 35, "测试部", 6400.0, LocalDateTime.of(2017, 3, 20, 14, 0, 0)));
    }};

    /**
     * 基于多条限流
     *  1.接口总限流每秒3个请求
     *  2.每个用户限流每秒1个请求
     * @param id
     * @return
     */
    @RateLimiters(value = {
            @RateLimiter(mode = RateType.OVERALL, rate = 3, rateInterval = 1, showPromptMsg = "系统繁忙，请稍后再试"),
            @RateLimiter(keys = {"#id"}, mode = RateType.OVERALL, rate = 1, rateInterval = 1, showPromptMsg = "您查询太快了，请稍后再试")
    })
    @RequestMapping("/findById/{id}")
    public ApiResponseDto<UserDto> findById(@PathVariable("id") String id) {
        UserDto userDto = map.getOrDefault(id, null);
        if (userDto != null) {
            return ApiResponseDto.success(userDto);
        }
        return ApiResponseDto.noData("未查询到数据");
    }



    @RateLimiter(mode = RateType.OVERALL, rate = 10, rateInterval = 1, rateIntervalUnit = TimeUnit.MINUTES ,showPromptMsg = "系统繁忙，请稍后再试")
    @RequestMapping("/findByIdAndMin/{id}")
    public ApiResponseDto<UserDto> findByIdAndMin(@PathVariable("id") String id) {
        UserDto userDto = map.getOrDefault(id, null);
        if (userDto != null) {
            return ApiResponseDto.success(userDto);
        }
        return ApiResponseDto.noData("未查询到数据");
    }


}
